package org.easy.control.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.easy.common.constant.TipConstant;
import org.easy.common.domain.SysUserDO;
import org.easy.common.util.EncryptUtil;
import org.easy.common.vo.SysUserVO;
import org.easy.module.service.SysUserService;

import org.easy.shiro.util.ShiroUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @ClassName: UserController
 * @Description: 用户Controller
 * @Author zhouzhixin
 * @Date 2021/9/26
 * @Version 1.0
 */
@Slf4j
@RequestMapping("/user")
@Controller
public class SysUserController {

    SysUserService sysUserService;

    @Autowired
    public void init(SysUserService sysUserService) {
        this.sysUserService = sysUserService;
    }

    /**
     * <p>登录</p>
     *
     * @param email
     * @param password
     * @param rememberMe
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/9/29 10:43
     */
    @PostMapping("login")
    public String login(@RequestParam(value = "email") String email, @RequestParam(value = "password") String password
            , @RequestParam(value = "rememberMe", required = false) String rememberMe, Model model) {
        log.info("登录---start");
        try {
            // 从SecurityUtils里边创建一个subject
            log.info("rememberMe:{}", rememberMe);
            Subject subject = SecurityUtils.getSubject();
            SysUserDO sysUserDO = sysUserService.getOne(new QueryWrapper<SysUserDO>().lambda().eq(SysUserDO::getEmail, email));
            if (null == sysUserDO) {
                model.addAttribute("loginTip", "邮箱为" + email + "的用户不存在");
                return "redirect:/sign-in";
            }
            // 在认证提交前准备 token（令牌）
            UsernamePasswordToken token = new UsernamePasswordToken(sysUserDO.getUsername()
                    , EncryptUtil.encrypt(password, sysUserDO.getSalt()));
            if ("on".equals(rememberMe)) {
                token.setRememberMe(true);
            }
            // 执行认证登陆
            subject.login(token);
            if (subject.isAuthenticated() && "0".equals(sysUserDO.getDeleted())) {
                return "redirect:/dict";
            } else if (subject.isAuthenticated() && "1".equals(sysUserDO.getDeleted())) {
                // 如果用户注册后未激活则跳转到激活页面
                return "redirect:/email-check";
            } else {
                token.clear();
                throw new AuthenticationException("登录失败");
            }
        } catch (Exception e) {
            log.error("登录过程出现异常", e);
        } finally {
            log.info("登录---end");
        }
        return "redirect:/sign-in";
    }

    /**
     * <p>注册</p>
     *
     * @param sysUserVO
     * @param model
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/9/29 10:43
     */
    @PostMapping("register")
    public String register(SysUserVO sysUserVO, Model model) {
        log.info("注册---start");
        try {
            SysUserDO sysUserDO = new SysUserDO();
            BeanUtils.copyProperties(sysUserVO, sysUserDO);
            model.addAttribute("registerTip", sysUserService.register(sysUserDO));
        } catch (Exception e) {
            log.error("注册过程出现异常", e);
        } finally {
            log.info("注册---end");
        }
        return "redirect:/sign-in";
    }

    /**
     * <p>注册时验证是否存在</p>
     *
     * @param sysUserVO
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/9/29 11:20
     */
    @ResponseBody
    @PostMapping("checkUserInfo")
    public String checkUserInfo(SysUserVO sysUserVO) {
        log.info("验证用户是否存在---start");
        try {
            SysUserDO sysUserDO = new SysUserDO();
            BeanUtils.copyProperties(sysUserVO, sysUserDO);
            return sysUserService.checkUserInfo(sysUserDO);
        } catch (Exception e) {
            log.error("验证用户信息出现异常", e);
        } finally {
            log.info("验证用户是否存在---end");
        }
        return null;
    }

    /**
     * <p>激活用户</p>
     *
     * @param checkCode
     * @return java.lang.String
     * @author zhouzhixin
     * @date 2021/9/30 14:51
     */
    @ResponseBody
    @PostMapping("activation")
    public String activation(@RequestParam("checkCode") String checkCode) {
        log.info("激活用户---start");
        try {
            SysUserDO sysUserDO = sysUserService.getOne(new QueryWrapper<SysUserDO>().lambda().eq(SysUserDO::getUsername
                    , ShiroUtil.getUser()));
            // 判断登录用户是否存在
            if (null != sysUserDO) {
                return sysUserService.activation(sysUserDO, checkCode);
            } else {
                return TipConstant.USER_NOT_EXIST;
            }
        } catch (Exception e) {
            log.error("激活过程出现异常", e);
        } finally {
            log.info("激活用户---end");
        }
        return TipConstant.ACTIVATION_UNKNOW_ERROR;
    }

}
